package de.rj.urwalking.tasks;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;
import de.rj.urwalking.R;
import de.rj.urwalking.util.ExperimentManager;
import de.rj.urwalking.util.PrefUtil;

public class SaveExperimentTask extends AsyncTask<Boolean, String, Integer> {

	private Context context;
	private ProgressDialog progressDialog;
	private boolean closeAfterSaving = false;

	public SaveExperimentTask(Context context, boolean finishAfterSaving) {
		this.context = context;
		this.closeAfterSaving = finishAfterSaving;

	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		progressDialog = ProgressDialog.show(context, "", context.getString(R.string.saving_data), true, false);

	}

	@Override
	protected Integer doInBackground(Boolean... params) {

		// check preferences if we actually want to save the data
		boolean saveData = PrefUtil.readBoolean(R.string.key_pref_test_mode_save_data, context, true);
		return ExperimentManager.getInstance().finishExperiment(saveData);
	}

	@Override
	protected void onPostExecute(Integer result) {
		super.onPostExecute(result);

		progressDialog.dismiss();

		switch (result) {
		case ExperimentManager.SAVING_SUCCESS:
			Toast.makeText(context, R.string.data_saved_successfully, Toast.LENGTH_SHORT).show();
			ActivityCompat.invalidateOptionsMenu((Activity) context);
			if (closeAfterSaving) {
				((Activity) context).finish();
			}
			break;
		case ExperimentManager.SAVING_ERROR:
			Toast.makeText(context, R.string.error_saving_data, Toast.LENGTH_SHORT).show();
			ActivityCompat.invalidateOptionsMenu((Activity) context);
			break;
		case ExperimentManager.SAVING_ABORTED:
			Toast.makeText(context, R.string.saving_data_aborted, Toast.LENGTH_SHORT).show();
			ActivityCompat.invalidateOptionsMenu((Activity) context);
			break;
		}

	}

}
